package com.wongsir.javatool.base64Util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;

/**
 * @Description: base64编码转换工具类
 * @author hjd
 * @date 2018年7月2日
 */
public class Base64Util {
	
	
	/**
	 * 文件流转base64字符串
	 */
	public static String streamToBase64Str(InputStream in) throws Exception{
		String base64Str = null;
		try {
			byte[] bytes = new byte[in.available()];
			in.read(bytes);
			base64Str = Base64Encoder.encode(bytes);
			in.reset();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return base64Str;
	}
	
	/**
	 * 文件流转base64字符串
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public static String streamToBase64Str1(InputStream in) throws Exception{
		byte[] buf = new byte[1024];
		int len = -1;
		int size = 0;
		String base64Str = null;
		try {
			while((len = in.read(buf))!= -1) {
				size += len;
			}
			byte[] bytes = new byte[size];
			in.read(bytes);
			base64Str = Base64Encoder.encode(bytes);
			in.reset();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return base64Str;
	}
	
	/**
	 * base64字符串转文件流
	 * @param base64Str
	 * @return
	 */
	public static ByteArrayInputStream base64ToStream(String base64Str){
		byte[] bytes = Base64Decoder.decode(base64Str);
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		return in;
	}
	
}
